package com.oocl.homework.format.command;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.oocl.homework.format.comparator.CustomerBirthdayComparator;
import com.oocl.homework.format.comparator.CustomerIdComparator;
import com.oocl.homework.format.data.DataCustomerImpl;
import com.oocl.homework.format.loader.DataLoader;
import com.oocl.homework.format.loader.DataLoaderImpl;
import com.oocl.homework.format.moel.Customer;
import com.oocl.homework.format.processor.DataProcessor;
import com.oocl.homework.format.processor.DataProcessorImpl;

public class CommandProcessorImpl implements CommandProcessor {

	@Override
	public String process(String str) {
		if (str.equals("")) {
			return "Unreconized please reinput";
		}
		Pattern pattern = Pattern.compile("(L|C){1}\\s+((line)|(xml))\\s+{1}((id)|(birth))");
		Matcher matcher = pattern.matcher(str);
		if (matcher.find()) {
			String[] ss = matcher.group().split("\\s+");
			if (ss[0].equals("C")) {
				return createCommand(ss[1], ss[2]);
			}else{
				return lookCommand(ss[1], ss[2]);
			}
		}else{
			return new DataLoaderImpl().load(str);
		}
	}
	
	public String lookCommand(String format,String compStr){
		DataProcessor dp=new DataProcessorImpl(DataCustomerImpl.getInstance().getCustomers(), format);
		Comparator<Customer> comp =null;
		if (compStr.equals("id")) {
			comp = new CustomerIdComparator();
		}
		if (compStr.equals("birth")) {
			comp = new CustomerBirthdayComparator();
		}
		StringBuilder sb=dp.process(comp);
		return sb.toString();
	}
	
	public String createCommand(String format,String compStr){
		DataProcessor dp=new DataProcessorImpl(DataCustomerImpl.getInstance().getCustomers(), format);
		Comparator<Customer> comp =null;
		if (compStr.equals("id")) {
			comp = new CustomerIdComparator();
		}
		if (compStr.equals("birth")) {
			comp = new CustomerBirthdayComparator();
		}
		StringBuilder sb=dp.process(comp);
		OutputStream out = null;
			try {
				if (format.equals("line")) {
				out = new FileOutputStream("customers"+compStr+".txt");
			}else{
				out = new FileOutputStream("customers"+compStr+".xml");
			}
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(out));
			bWriter.write(sb.toString());
			bWriter.close();
			return "create success";
			} catch (IOException e) {
				// log here
				e.printStackTrace();
				return "create fail";
			}
		
	}
	
	
	public String addCommand(String str){
		DataLoader dataLoader = new DataLoaderImpl();
		return dataLoader.load(str);
	}

}
